package com.tran.app.viewmodel

import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.tran.app.MyApp
import com.tran.app.dao.AppDatabase
import com.tran.app.data.Course
import com.tran.app.data.CourseSelection
import com.tran.app.utils.show
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.update
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext


class CSScreenVM:ViewModel() {


    fun search(search: String) {
        viewModelScope.launch {
            withContext(Dispatchers.IO){
                val course = AppDatabase.getInstance(MyApp.instance).courseDao().getCoursesByCName(search)
                _uidata.update {
                    course.toMutableList()
                }
            }
        }
    }
    fun chooseCourse(it: Course) {
        viewModelScope.launch {
            var exitReason: String? = null // 用于记录退出原因的标志变量
            withContext(Dispatchers.IO) {
                val id = AppDatabase.getInstance(MyApp.instance).userInfoDao().getUserByName(MyApp.user)!!.id
                val cour = CourseSelection(0, id, it.id)
                val list = AppDatabase.getInstance(MyApp.instance).CourseSelectionDao().getCourseSelectionsByStudentId(id)
                if (list.size >= 3) {
                    exitReason = "选课最多不能超过三门" // 设置退出原因
                    return@withContext
                }
                for (item in list) {
                    if (it.id == item.courseId) {
                        exitReason = "你已经选了该课程" // 设置退出原因
                        return@withContext
                    }
                }
                if (exitReason == null) {
                    // 如果没有退出原因，则插入课程选择
                    AppDatabase.getInstance(MyApp.instance).CourseSelectionDao().insert(cour)
                }
            }
            // 检查退出原因并显示相应的消息
            if (exitReason != null) {
                withContext(Dispatchers.Main) {
                    show(exitReason!!) // 显示退出原因
                }
                return@launch // 退出整个 launch 协程
            }
            withContext(Dispatchers.Main) {
                show("选课成功") // 没有退出原因，显示选课成功消息
            }
        }
    }

    val _uidata = MutableStateFlow(mutableListOf<Course>())
    val uidata: StateFlow<List<Course>> = _uidata.asStateFlow()
    init {
        viewModelScope.launch {
            withContext(Dispatchers.IO){
                val data = AppDatabase.getInstance(MyApp.instance).courseDao().getCourses()
                _uidata.update {
                    data.toMutableList()
                }
            }
        }
    }

}